import { defineStore } from "pinia";
import { AUTH_API } from "@/config/config";
import type { UserState } from "../interface";
import { http } from "hdzk-tools";

interface userType {
	realName: string;
	/** 工号 */
	username: string;
	[x: string]: any;
}
const getUserNameApi = (data: { userNames: string[] }) => http.post<userType[]>(`${AUTH_API}/user/getUsersByUserNames`, data);
export const UserStore = defineStore({
	id: "UserStore",
	state: (): UserState => ({
		userNameMap: {}
	}),
	actions: {
		/** 获取name
		 * @param ids 工号数组
		 * @returns name数组
		 */
		async getUserNameMap(ids: string[]) {
			// 在userNameMap中找到id对应的name, 如果没有则提取新数组
			const newIds = ids.filter(id => !this.userNameMap[id]);
			// 如果有没获取到的id, 则请求接口获取
			if (newIds.length) {
				const { data } = await getUserNameApi({ userNames: [...new Set(newIds)] });
				// 遍历data，将对应的id和name存入userNameMap
				data.forEach((user: userType) => {
					this.userNameMap[user.username] = user.realName;
				});
			}
			const nameArr = ids.map(id => this.userNameMap[id]);
			return nameArr;
		},
		/** 获取一个人的name */
		async getUserName(id: string) {
			const map = await this.getUserNameMap([id]);
			return map;
		}
	}
});
